package com.bob.light.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.bob.light.*
import com.bob.light.config.AppConfig
import com.bob.light.config.UserConfig
import com.tuya.smart.android.user.bean.User
import kotlinx.android.synthetic.main.app_activity_login.*

class LoginActivity : BackPressedWrapperActivity() {

    private val mEtToWatcherMap = hashMapOf<EditText, TextWatcher>()
    private val mLoginBtnState = MutableLiveData<Boolean>()

    companion object {

        @JvmStatic
        fun navigation(activity: AppCompatActivity?) {
            activity?.let { context ->
                val intent = Intent(context, LoginActivity::class.java)
                context.startActivity(intent)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.app_activity_login)
        initView()
    }

    private fun initView() {
        registerEditTextWatcher(et_phone)
        registerEditTextWatcher(et_pwd)
        observeLoginBtn()
        observeRegisterBtn()
        observeKeyDown()
    }

    /**
     * @param editText phoneEditText or codeEditText
     */
    private fun registerEditTextWatcher(editText: EditText?) {
        editText?.addTextChangedSampleListener {
            val isLegalMobile = (et_phone?.isLegalMobile)?:false
            val pwd = (et_pwd?.text?.toString())?:""
            mLoginBtnState.value = (isLegalMobile && (!TextUtils.isEmpty(pwd)))
        }?.let { newWatcher ->
            val watcher = mEtToWatcherMap[editText]
            if (watcher != null) {
                editText.removeTextChangedListener(watcher)
            }
            mEtToWatcherMap[editText] = newWatcher
        }
    }

    /**
     * @desc 对登陆按钮的状态监听 与 点击事件
     */
    private fun observeLoginBtn() {
        app_activity_login_btn?.isEnabled = false
        mLoginBtnState.observe(this@LoginActivity, Observer { isEnabled ->
            app_activity_login_btn?.isEnabled = isEnabled
        })
        app_activity_login_btn?.setOnSingleClickListener {
            val phone = (et_phone?.mobile)?:""
            val pwd = (et_pwd?.text?.toString())?:""
            loginIn(phone, pwd)
        }
    }

    /**
     * @desc 登陆操作
     */
    private fun loginIn(phone: String, pwd: String) {
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd)) {
            return
        }
        TuyaHomeSDKHelper.loginWithPhonePasswordInChina(phone, pwd,
                successCallback = { user ->
                    "登录成功".toast()
                    saveUserInfo(user)
                    navigationNextActivity()
                }, failCallback = {
            "登录失败".toast()
        })
    }

    private fun navigationNextActivity() {
        val firstRegister = AppConfig.isFirstRegister()
        if (firstRegister) {
            FamilyManagerActivity.navigation(this@LoginActivity)
        } else {
            MainActivity.navigation(this@LoginActivity)
        }
        finish()
    }

    /**
     * @desc 保存用户信息
     */
    private fun saveUserInfo(user: User?) {
        UserConfig.save(user)
    }

    /**
     * @desc 跳转注册页面
     */
    private fun observeRegisterBtn() {
        fl_register?.setOnSingleClickListener {
            RegisterActivity.navigation(this@LoginActivity)
        }
    }

    /**
     * @desc 返回事件
     */
    private fun observeKeyDown() {
        fl_back_pressed?.setOnSingleClickListener {
            onBackPressed()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == RegisterActivity.REQUEST_CODE) {
            val phoneNumber = (data?.getStringExtra(RegisterActivity.PHONE_NUMBER))?:""
            if (!TextUtils.isEmpty(phoneNumber)) {
                et_phone.setText(phoneNumber)
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        mEtToWatcherMap.mapKeys {
            it.key.removeTextChangedListener(it.value)
        }
        super.onDestroy()
    }

}